﻿//-------------------------------------------------------------------------------------------------
// <copyright file="PersonalDictionarySerializer.cs" company="Anthony Adam">
// Copyright (c) Anthony Adam 2015. All rights reserved.
// </copyright>
//-------------------------------------------------------------------------------------------------
namespace SuperStarRounds.Classes.FileIO
{
  using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Xml.Serialization;

  public static class PersonalDictionarySerializer
  {
    /// <summary>
    /// Save personal dictionary.
    /// </summary>
    /// <param name="list">String list of words to save</param>
    /// <param name="fileName">Filename to save to</param>
    public static void SerializePersonalDictionary(List<string> list, string fileName)
    {
      var serializer = new XmlSerializer(typeof(List<string>));
      var stream = File.OpenWrite(fileName);
      try
      {
        serializer.Serialize(stream, list);
        stream.Close();
      }
      catch (Exception)
      {
        // if serialize fails, close the stream
        stream.Close();
      }
    }

    /// <summary>
    /// Load personal dictionary.
    /// </summary>
    /// <param name="fileName">File name containing words</param>
    /// <returns>IEnumerable list of personal dictionary words</returns>
    public static IEnumerable<string> DeserializePersonalDictionary(string fileName)
    {
      if (!File.Exists(fileName)) return new List<string>();

      var serializer = new XmlSerializer(typeof(List<string>));
      var stream = File.OpenRead(fileName);
      try
      {
        var loadedList = (List<string>)serializer.Deserialize(stream);
        stream.Close();
        return loadedList;
      }
      catch (Exception)
      {
        // if serialize fails, close the stream
        stream.Close();
        return new List<string>();
      }
    }
  }
}